<?php
/**
 * Created by PhpStorm.
 * Script Name: Tpzs.php
 * Create: 2022/4/18 10:38
 * Description: 推品助手处理器
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\bot\controller;

use app\admin\model\BotMember;
use app\common\model\tpzs\Config;
use app\common\model\tpzs\Gather;
use app\common\model\tpzs\Team;
use app\constants\Bot;
use ky\Helper;
use ky\Jtt;
use ky\Logger;

class Tpzs extends Addon
{
    /**
     * @var Config
     */
    private $configM;
    /**
     * @var Team
     */
    private $teamM;
    /**
     * @var Gather
     */
    private $gatherM;

    public function init($options = [])
    {
        parent::init($options); // TODO: Change the autogenerated stub
        $this->configM = new Config();
        $this->teamM = new Team();
        $this->gatherM = new Gather();
        $this->memberM = new BotMember();
        return $this;
    }

    /**
     * 机器人主动事件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function deviceCallbackHandle(){
        if(!empty($this->groupWxid)){
            $this->groupChatHandle();
        }
    }

    /**
     * 群聊处理器
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function groupChatHandle(){
        $conf = $this->configM->getConf(['admin_id' => $this->bot['admin_id']]);
        if((!empty($conf['time_on']) && $conf['time_on'] > date('H:i')) ||
            (!empty($conf['time_off']) && $conf['time_off'] < date('H:i'))){
            return true;
        }

        $content = $this->content;
        $group_wxid = $this->groupWxid;

        //一、群发
        //1、判断当前群组是否是某个用户的中央调度群
        if($group = $this->gatherM->getGather([
            'group_wxid' => $group_wxid,
            'from_wxid' => $this->fromWxid,
            'bot_wxid' => $this->botWxid
        ])){
            //2.取出机器人负责的群并转发
            $groups = explode(',', $group['wxids']);
            /**
             * @var $redis \Redis
             */
            $redis = get_redis();
            switch($content['type']){
                case Bot::MSG_TEXT:
                    if(strpos($content['msg'], 'jd.com') !== false){//jd
                        $jtt = new Jtt(['appid' => $conf['jtt_appid'], 'appkey' => $conf['jtt_appkey']]);
                        $reply_content = $content['msg'];
                        foreach ($groups as $gid){
                            if($dest_group = $this->memberM->getOneJoin([
                                'alias' => 'm',
                                'join' => [
                                    ['tpzsGrouppos gp', 'gp.group_id=m.id'],
                                    ['tpzsPosition tp', 'gp.position_id=tp.id'],
                                    ['tpzsUnion tu', 'tu.id=tp.union_id']
                                ],
                                'where' => ['m.wxid' => $gid, 'gp.bot_id' => $this->bot['id']],
                                'field' => ['tu.unionid', 'tp.position_id']
                            ])) {
                                if($group['universal']){
                                    $rKey = $this->content['msg_id'].$dest_group['position_id'];
                                    if(! $reply_content = $redis->get($rKey)){
                                        $count = 0;
                                        do{
                                            $reply_content = $jtt->universal([
                                                'unionid' => $dest_group['unionid'],
                                                'positionid' => $dest_group['position_id'],
                                                'content' => $content['msg']
                                            ]);
                                            $count++;
                                            if($count >= 2) break;
                                        }while($reply_content === false);
                                        if($reply_content){
                                            $reply_content = $reply_content['chain_content'];
                                            $redis->setex($rKey, 300, $reply_content);
                                        }
                                    }
                                }
                                $this->botClient->sendTextToFriend([
                                    'robot_wxid' => $content['robot_wxid'],
                                    'to_wxid' => $gid,
                                    'msg' => $reply_content
                                ]);
                            }
                        }
                    }elseif (strpos($content['msg'], 'ckjr001.com') !== false){ //https://wx74161fcecb84d46c.wx.ckjr001.com/kpv2p/6m5oe8/?1649328453716=#/homePage/course/voice?courseId=2913528&ckFrom=5&extId=-1&refereeId=[推广人]
                        foreach ($groups as $gid){
                            if($dest_group = $this->memberM->getOneJoin([
                                'alias' => 'm',
                                'join' => [
                                    ['tpzsGrouppos gp', 'gp.group_id=m.id'],
                                    ['tpzsChannel channel', 'channel.id=gp.channel_id']
                                ],
                                'where' => ['m.wxid' => $gid, 'm.uin' => $this->bot['uin']],
                                'field' => ['channel.ckid']
                            ])) {
                                $rKey = $this->content['msg_id'].$dest_group['ckid'];
                                if(! $reply_content = $redis->get($rKey)){
                                    $reply_content = str_replace('[推广人]', $dest_group['ckid'], $this->content['msg']);
                                    $redis->setex($rKey, 300, $reply_content);
                                }
                                $this->botClient->sendTextToFriend([
                                    'robot_wxid' => $content['robot_wxid'],
                                    'to_wxid' => $gid,
                                    'msg' => $reply_content
                                ]);
                            }
                        }
                    }else{ //basic
                        $this->botClient->sendTextToFriends(['robot_wxid' => $content['robot_wxid'], 'to_wxid' => $groups, 'msg' => $content['msg']]);
                    }
                    break;
                case Bot::MSG_LINK:
                    switch ($this->bot['protocol']){
                        case Bot::PROTOCOL_WXWORK:
                        case Bot::PROTOCOL_MYCOM:
                            $msg = json_decode($this->content['msg'], true)['Link'][0];
                            //$url = strpos($content['msg'], 'ckjr001.com') !== false ? $msg['url'] : $msg['url']
                            $url = $msg['url'];
                            $res = $this->botClient->sendShareLinkToFriends([
                                'robot_wxid' => $content['robot_wxid'],
                                'to_wxid' => $groups,
                                'url' => $url,
                                'image_url' => empty($msg['image_url']) ? 'https://zyx.images.huihuiba.net/default-headimg.png' : $msg['image_url'],
                                'title' => $msg['title'],
                                'desc' => $msg['desc']
                            ]);
                            break;
                        default:
                            $this->botClient->forwardMsgToFriends([
                                'robot_wxid' => $this->botWxid,
                                'to_wxid' => $groups,
                                'msgid' => $this->content['msg_id']
                            ]);
                    }
                    break;
                default:
                    switch ($this->bot['protocol']){
                        case Bot::PROTOCOL_WXWORK:
                        case Bot::PROTOCOL_MYCOM:
                            $this->botClient->sendTextToFriends(['robot_wxid' => $content['robot_wxid'], 'to_wxid' => $groups, 'msg' => $content['msg']]);
                            break;
                        default:
                            $this->botClient->forwardMsgToFriends([
                                'robot_wxid' => $this->botWxid,
                                'to_wxid' => $groups,
                                'msgid' => $this->content['msg_id']
                            ]);
                    }
                    break;
            }
        }
        //二、关键词
        $this->keyword();
    }

    /**
     * 私聊处理器
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function privateChatHandle(){

    }

    /**
     * 关键词回复
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function keyword(){
        if(strpos($this->content['msg'], "@所有人") === false && strpos($this->content['msg'], "我要") === 0){ //主动搜商品
            //Logger::error($this->content);
            if($this->teamM->total([
                    'bot_id' => $this->bot['id'],
                    'groups' => ['like', "%".$this->groupWxid."%"]
                ]) && $dest_group = $this->memberM->getOneJoin([
                    'alias' => 'm',
                    'join' => [
                        ['tpzsGrouppos gp', 'gp.group_id=m.id'],
                        ['tpzsPosition tp', 'gp.position_id=tp.id'],
                        ['tpzsUnion tu', 'tu.id=tp.union_id']
                    ],
                    'where' => ['m.wxid' => $this->groupWxid],
                    'field' => ['tu.unionid', 'tp.position_id']
                ])){
                $msg = explode("我要", $this->content['msg']);
                if(!empty($msg[1])){
                    $keyword = trim($msg[1]);
                    $this->botClient->sendTextToFriend([
                        'robot_wxid' => $this->content['robot_wxid'],
                        'to_wxid' => $this->groupWxid,
                        'msg' => "@".$this->content['from_name'] . "[emoji=\\u2005] ".$this->searchGoods([
                                'keyword' => $keyword,
                                'unionid' => $dest_group['unionid'],
                                'positionid' => $dest_group['position_id'],
                            ])
                    ]);
                }
            }
        }
    }

    /**
     * 用户主动搜索
     * @param array $params
     * @return string
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function searchGoods($params = []){
        $conf = $this->configM->getConf(['admin_id' => $this->bot['admin_id']]);
        $keyword = $params['keyword'];
        $page_size = empty($params['page_size']) ? 3 : $params['page_size'];
        $unionid = $params['unionid'];
        $positionid = $params['positionid'];
        $jtt = new Jtt(['appid' => $conf['jtt_appid'], 'appkey' => $conf['jtt_appkey']]);
        $res = $jtt->jdGoodsQuery([
            'v' => 'v3', 'keyword' => $keyword, 'sortName' => 'inOrderCount30Days', 'sort' => 'desc', 'isCoupon' => 1,
            'pageSize' => $page_size
        ]);

        $template = "[商品标题]
京东价：[商品原价]元
抢购价：[优惠价]元
领券+下单：[抢购链接]";
        $content = "暂未找到相关内容，您可以点击以下链接自助查询哦：
https://union-click.jd.com/jdc?e=618%7Cpc%7C&p=JF8BAOkJK1olXDYDZBoCUBVIMzZNXhpXVhgcDVpCVFRMVnBaRQcLDlZRAAMoUAMJaDtMWUVzBnF0ACcPYABWAxJTTjt9HnUGFigtWC9rXz8WQwRACU8dDRsBVUVWUzlcYw4ZBFhHZBkLYAtWBjp-eCBjIhwECQ5DEgBzZR8EF2sQXQcDU1ddC04eM2wJGF8UXAQKU1ttOEsUMyRmGmsXXAcHV1lYDEgTM28PHlIcVAABUF5UDk4nBG8BKwBAMwNEHz0jCCNzRBNAeF5QHzYyZF1tD0seF2l6WgkBW3QyZF9tC3tIRzJVK1kUXAILZA
";
        if(!empty($res['totalCount'])){
            $content = "为您查询到以下".count($res['goods'])."个商品：\r\n\r\n";
            foreach ($res['goods'] as $k => $goods){
                $link = $goods['goods_link'];
                if(!empty($goods['couponInfo']['couponList'][0]['discount_link'])){
                    $coupon_link = $goods['couponInfo']['couponList'][0]['discount_link'];
                    $link = $goods['goods_link'] . "\r\n" . $coupon_link;
                }

                if($k + 1 >= count($res['goods'])){
                    $link .= "\r\n-------------------------------------------\r\n\r\n[玫瑰]如果您对查询结果不满意，可以自主查询：\r\nhttps://union-click.jd.com/jdc?e=618%7Cpc%7C&p=JF8BAOkJK1olXDYDZBoCUBVIMzZNXhpXVhgcDVpCVFRMVnBaRQcLDlZRAAMoUAMJaDtMWUVzBnF0ACcPYABWAxJTTjt9HnUGFigtWC9rXz8WQwRACU8dDRsBVUVWUzlcYw4ZBFhHZBkLYAtWBjp-eCBjIhwECQ5DEgBzZR8EF2sQXQcDU1ddC04eM2wJGF8UXAQKU1ttOEsUMyRmGmsXXAcHV1lYDEgTM28PHlIcVAABUF5UDk4nBG8BKwBAMwNEHz0jCCNzRBNAeF5QHzYyZF1tD0seF2l6WgkBW3QyZF9tC3tIRzJVK1kUXAILZA";
                }else{
                    $link .= "\r\n-------------------------------------------\r\n";
                }

                $count = 0;
                do{
                    $reply_content = $jtt->universal([
                        'unionid' => $unionid,
                        'positionid' => $positionid,
                        'content' => $link
                    ]);
                    $count++;
                    if($count >= 2) break;
                }while($reply_content === false);

                if($reply_content && !empty($reply_content['chain_content'])){
                    $link = $reply_content['chain_content'];
                }else{
                    $link = "https://".$goods['goods_link'] . "\r\n-------------------------------------------\r\n";
                }

                $temp_content = str_replace(
                    ['[商品标题]', '[商品原价]', '[优惠价]', '[抢购链接]'],
                    [$goods['skuName'], $goods['priceInfo']['goods_price'], $goods['priceInfo']['lowestCouponPrice'], $link],
                    $template
                );

                $content .= $temp_content;
            }
        }else{
            $reply_content = $jtt->universal([
                'unionid' => $unionid,
                'positionid' => $positionid,
                'content' => $content,
                'v' => 'v2'
            ]);
            $content = $reply_content['chain_content'];
        }
        return $content;
    }
}